package com.ocom.amqp.builder;

import com.ocom.amqp.core.DelayQueue;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;

import java.util.HashMap;
import java.util.Map;

public class DelayQueueBuilder extends AbstractAssemblyBuilder<DelayQueue> {

    public DelayQueueBuilder(RabbitAdmin rabbitAdmin) {
        super(rabbitAdmin);
    }

    @Override
    public void build(DelayQueue assembly) {
        String businessName = assembly.getBusinessName();
        String deadExchangeName = DEAD_PREFIX.concat(businessName).concat(EXCHANGE_SUFFIX);

        //create delay exchange
        Exchange delayExchange = new DirectExchange(assembly.getSendExchangeName(), true, false);
        //create delay queue
        Map<String, Object> argument = new HashMap<>();
        if (assembly.getExpiration() != null) {
            argument.put("x-message-ttl", assembly.getExpiration());
        }
        argument.put("x-dead-letter-exchange", deadExchangeName);
        Queue delayQueue = new Queue(DELAY_PREFIX.concat(businessName).concat(QUEUE_SUFFIX), true, false, false,
                argument);
        //create dead exchange
        Exchange deadExchange = new DirectExchange(deadExchangeName, true, false);
        //create dead queue
        Queue deadQueue = new Queue(assembly.getListenQueueName(), false, false, false);

        //binding
        Binding delayBinding = BindingBuilder.bind(delayQueue).to(delayExchange).with(assembly.getRoutingKey())
                .noargs();

        Binding deadBinding = BindingBuilder.bind(deadQueue).to(deadExchange).with(assembly.getRoutingKey()).noargs();

        this.rabbitAdmin.declareQueue(delayQueue);
        this.rabbitAdmin.declareQueue(deadQueue);
        this.rabbitAdmin.declareExchange(delayExchange);
        this.rabbitAdmin.declareExchange(deadExchange);
        this.rabbitAdmin.declareBinding(delayBinding);
        this.rabbitAdmin.declareBinding(deadBinding);
    }
}
